const User = require('../model/user.model')


class UserService {
    /**
     * 创建用户
     */
    async createUser (UserData) {
        // 插入数据
        try {
            const res = await User.create(UserData)
            return res
        } catch (error) {
            return {
                errorFlag: 'error',
                errorCode: error.parent.code,
                message: error.parent.sqlMessage,
            }
        }
    }
    /**
     * 按照某一字段查找表
     */
    async getUserInfo ({ user_account, user_name, role, user_tel, openid }) {
        const whereOpt = {}
        // 短路运算 值存在就拷贝进whereOpt
        user_name && Object.assign(whereOpt, { user_name })
        user_account && Object.assign(whereOpt, { user_account })
        role && Object.assign(whereOpt, { role })
        user_tel && Object.assign(whereOpt, { user_tel })
        openid && Object.assign(whereOpt, { openid })
        const res = await User.findAll({ where: whereOpt })
        return res
    }

    async getUserByAccount (user_account) {
        const res = await User.findOne({ where: { user_account } })
        return res
    }

    /**
     * 获取用户列表
     */
    async getUserList (whereOpt, offect = 0, limit = 100) {
        const { count, rows } = await User.findAndCountAll({ where: whereOpt, offset: offect * 1, limit: limit * 1 })
        return { count, rows }
    }

    /**
     * 修改用户信息
     */
    async modifyByUserAccount (modifyData, user_account) {
        try {
            const res = await User.update(modifyData, { where: { user_account } })
            return res
        } catch (error) {
            return {
                errorFlag: 'error',
                message: error,
            }
        }
    }

    /**
     * 按照user_account 删除一个用户
     */
    async deleteByUserAccount (user_account) {
        try {
            const res = await User.destroy({ where: { user_account } })
            return res
        } catch (error) {
            return {
                errorFlag: 'error',
                message: error,
            }
        }
    }

    /**
     * 删除某角色时，绑定该角色的用户更换角色
     */
    async modifyUserBindRole (role_code, new_role_code) {
        try {
            const res = await User.update({ role: new_role_code }, { where: { role: role_code } })
            return res
        } catch (error) {
            return {
                errorFlag: 'error',
                message: error,
            }
        }
    }
}

module.exports = new UserService()